import React, { useEffect, useState } from 'react'
import { BrowserRouter, Router, Switch } from 'react-router-dom'
import { ConfigProvider, Spin } from 'antd'
import zhCN from 'antd/lib/locale/zh_CN'
import FrontendAuth from './components/frontend-auth'
import Index from './pages/index'
import Login from './pages/login'
import { history } from '@/plugins/history'
import store from '@/store'

const routerMap = [
  {
    path: '/',
    name: 'Index',
    meta: {
      title: '首页'
    },
    component: Index
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登陆'
    },
    component: Login
  }
]

const Render = (props: any) => {
  const [loading, setLoading] = useState<boolean>(false)
  const [config, dispatcher] = store.useModel('initState')

  useEffect(() => {
    dispatcher.init()
      .finally(() => {
        setLoading(false)
      })
  }, [dispatcher])

  if (loading) {
    return (
      <div className='layout-content'>
        <Spin size='large' />
      </div>
    )
  } else {
    return (
      <Router history={history}>
        <Switch>
          <FrontendAuth
            config={config}
            routerConfig={routerMap}
            location={props.location}
          />
        </Switch>
      </Router>
    )
  }
}

const App = (props: any) => {
  return (
    <BrowserRouter>
      <ConfigProvider locale={zhCN}>
        <store.Provider>
          <Render />
        </store.Provider>
      </ConfigProvider>
    </BrowserRouter>
  )
}

export default App
